<template>
  <div class="buyContainer">
    <!-- 导航栏 -->
    <van-nav-bar
      title="提交订单"
      left-text="返回"
      left-arrow
      :border="false"
      @click-left="back"
      class="navbar"
    />
    <!-- 商品信息 -->
    <div class="good">
      <!-- 顶部 -->
      <div class="title">
        <div class="name">{{ shopInfo.shopName }}{{ shopInfo.title }}</div>
        <div class="count">x1</div>
      </div>
      <!-- 中间 -->
      <div class="content">
        <div class="numbox">
          <div class="text">数量</div>
          <!-- 步进器 -->
          <van-stepper v-model="value" integer />
        </div>
        <div class="pricebox">
          <div class="text">小计</div>
          <div class="price"><i>¥</i>{{ totalPrice }}</div>
        </div>
      </div>
      <!-- 优惠券单元格 -->
      <van-coupon-cell />
    </div>
    <!-- 立即登录 -->
    <div class="onceLogin" v-if="!isLogin">
      <div class="title">立即登录</div>
      <div class="content">
        <van-form>
          <!-- 手机号 -->
          <van-cell-group>
            <van-field
              v-model="phone"
              label="86"
              left-icon="arrow-down"
              placeholder="请输入手机号"
              type="tel"
              class="phoneBox"
              :rules="[{ validator: rulesTel, trigger: 'onBlur' }]"
            >
              <template #button>
                <van-button size="small" :disabled="!isSend" @click="getCode"
                  >发送验证码</van-button
                >
              </template>
            </van-field>
          </van-cell-group>
          <!-- 短信验证码 -->
          <van-field
            v-model="code"
            center
            clearable
            label="验证码"
            placeholder="请输入验证码"
            :rules="[
              {
                validator: rulesCode,
                trigger: 'onBlur',
              },
            ]"
          >
          </van-field>
        </van-form>
      </div>
    </div>
    <!-- 何时可退 -->
    <div class="cancelTime">
      <van-icon name="checked" color="#65C07A" />
      <i>支持随时退</i>
      <van-icon name="checked" color="#65C07A" />
      <i>支持过期退</i>
    </div>
    <!-- 去支付 -->
    <div class="toPay">
      <button @click="onPay">去支付{{ totalPrice }}元</button>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapState } from "vuex";
import { Toast } from "vant";
export default {
  name: "Buy",
  data() {
    return {
      value: 1, //商品数量
      phone: "", //手机号
      code: "", //短信验证码
      successCode: "", //登录成功用的验证码
      isSend: false, //是否可以发送验证码
      totalPrice: "", //商品总价
    };
  },
  // 内置路由守卫
  beforeRouteEnter: (to, from, next) => {
    const { name } = from;
    if (name === "likedetail") {
      next();
    } else {
      next({
        ...from,
      });
    }
  },
  computed: {
    ...mapState({
      shopInfo: (state) => state.likeDetail.shopInfo,
    }),
    ...mapState({
      pre: (state) => state.likeDetail.pre,
    }),
    // 是否已经登录
    isLogin() {
      return localStorage.getItem("token") ? true : false;
    },
  },
  watch: {
    // 监视商品数量的变化
    value: {
      immediate: true,
      handler(val) {
        if (Boolean(Number(val)) == false || val <= 0) {
          return;
        }
        // 商品总价
        let val1 = val * this.pre.dealgroupPrice0;
        this.totalPrice = Math.round(val1 * 100) / 100;
      },
    },
  },
  methods: {
    //   返回详情页
    back() {
      this.$router.replace("/likeDetail");
    },
    // 校验手机号
    rulesTel(val, rule) {
      if (!val) {
        rule.message = "";
        // 不可以发送验证码
        this.isSend = false;
        return false;
      }
      if (val.length < 11 || val.length > 11) {
        rule.message = "请输入正确的手机号";
        // 不可以发送验证码
        this.isSend = false;
        return false;
      }
      // 可以发送验证码
      this.isSend = true;
      return true;
    },
    rulesCode(val, rule) {
      if (val !== this.successCode) {
        rule.message = "请输入正确的验证码";
        return false;
      }
      return true;
    },
    // 发请求,得到验证码
    async getCode() {
      const result = await this.$API.getCode();
      if (result.code === 200) {
        this.code = result.msg;
      }
      this.successCode = result.authCode;
      console.log(result);
    },
    // 去支付
    async onPay() {
      // 如果已经登录
      if (this.isLogin) {
        // 保存购买的商品信息
        if (!this.savePurchasedGood()) {
          return false;
        }
        Toast.success("支付成功");
        setTimeout(() => {
          this.$router.go(-1);
        }, 1000);
        return;
      }
      // 如果没有登录
      const { code } = this;
      let flag = 0;
      const result = await this.$API.login({
        phone: this.phone,
        authCode: code,
        flag,
      });
      if (result.code == 200) {
        localStorage.setItem("token", result.token);
        Toast.loading("登录成功");
        setTimeout(() => {
          Toast.clear();
          // 保存购买的商品信息
          if (!this.savePurchasedGood()) {
            return false;
          }
          Toast.success("支付成功");
          setTimeout(() => {
            this.$router.go(-1);
          }, 1000);
        }, 1000);
      } else {
        Toast.loading(result.msg);
      }
    },
    // 收集购买的商品数据
    async savePurchasedGood() {
      // 保存本页数据
      const purchasedGood = {
        img: this.shopInfo.defaultPic.imgUrl,
        shopName: this.shopInfo.shopName,
        goodName: this.shopInfo.title,
        count: this.value,
        totalPrice: this.totalPrice,
      };
      const result = await this.$API.addCart(purchasedGood);
      if (result.code !== 200) {
        Toast(result.msg);
        if(result.msg=="token过期"){
          Toast('请重新登录')
          this.$router.push('/register')
        }else{
          Toast('请重新尝试')
        }
        return false;
      }
      return true;
    },
  },
};
</script>

<style scoped lang="less">
.buyContainer {
  height: 100vh;
  background-color: #f0f0f0;

  i {
    font-style: normal;
  }

  h3 {
    margin: 0;
    color: #b5b5b5;
    font-size: 15px;
    font-weight: normal;
  }

  // 导航栏
  .navbar {
    background-color: #fff;

    /deep/ .van-nav-bar__left {
      padding: 0;
    }

    // 返回箭头
    /deep/ .van-nav-bar__arrow {
      font-size: 24px;
      margin: 0;
      color: #ff6633;
    }

    // 返回文字
    /deep/ .van-nav-bar__text {
      color: #000;
    }
  }

  //   商品信息
  .good {
    font-size: 16px;

    .title {
      display: flex;
      justify-content: space-between;
      padding: 0 15px;
      height: 40px;
      align-items: center;

      div {
        font-size: 16px;
        color: #666;
      }

      .name {
        // 限制文字长度
        width: 300px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }

    .content {
      background-color: #fff;
      padding: 0 15px;

      > div {
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 40px;
        border-bottom: 1px solid #f0f0f0;

        &:last-child {
          border: none;
        }
      }
    }

    /deep/ .van-cell {
      margin-top: 10px;
      padding: 10px 15px !important;
    }
  }

  // 立即登录
  .onceLogin {
    margin-top: 30px;

    .title {
      color: #3388bb;
      font-size: 16px;
      padding-left: 20px;
      margin-bottom: 10px;
    }

    .content {
      .phoneBox {
        /deep/ .van-field__label {
          width: 77px;
          height: 35px;
          line-height: 35px;
        }

        /deep/ .van-field__left-icon {
          line-height: 35px;
        }
      }
    }
  }

  // 何时可退
  .cancelTime {
    margin: 20px 15px;
    font-size: 16px;
    color: #69c27e;

    i {
      margin-right: 5px;
    }

    > div {
      margin-right: 10px;
    }
  }

  // 去支付
  .toPay {
    position: relative;

    button {
      position: absolute;
      left: 50%;
      margin-left: -170px;
      top: 0;
      width: 340px;
      height: 40px;
      border: none;
      background-color: #ff6633;
      color: #fff;
    }
  }
}
</style>